function buildTree() {
    /*
     * createTagUl(tag)
     * createWebpageLi(webpage)
     */
    console.log("tree.js buildTree : building the tree...");
    
    var $treeContainer=$("#tree");
    
    $("#tree").empty();
    
    //we go through the arTags array
    for (var i=0;i<arTags.length;i++) {
        
        var currentTag=arTags[i].tag;        
        var currentWebpageArray=arTags[i].arWebpages;                
        
        //we create the container for this tag
        var $parentTagLi=uiCreateTag(currentTag);
        var $parentTagUl=$("<ul class='collapsible'></ul>");
        
        //we go through the currentWebpageArray array
        for (var j=0;j<currentWebpageArray.length;j++) {
            var currentWebpage=currentWebpageArray[j];
            
            //we create the container for this webpage's title
            var $childrenWebpageLi=uiCreateWebpage(currentWebpage);
   
            //we append it
            $parentTagUl.append($childrenWebpageLi);
            
        }
        
        //we append the ul to the li
        $parentTagLi.append($parentTagUl);
   
        //and finally we add the li to the tree
        $treeContainer.append($parentTagLi);
    }
    
   
}

//returns a collapsible <li> element, which label is the value tag
function uiCreateTag(tag) {
    var tagLi=$('<li class="collapser collapsed">'+tag+'</li>');
    
    return tagLi;
}

function uiCreateWebpage(webpage) {
    var webpageLi=$('<li class="webpage-link" url="'+webpage.url
        +'" title="'+webpage.url+'">'
        +'<img src="img/link-out.png" class="webpage-link-out" title="Open this link in a new window" /> '
        +webpage.title+'</li>');
    
    return webpageLi;
}

/****************Tree events
 * 
 */

function loadTreeEvents() {
    $(".collapser").live("click",null,function() {
        $(this).find(".collapsible").toggle();
        
        $(this).toggleClass("collapsed");
        $(this).toggleClass("expanded");
        
    });
    
    $(".collapsible").live("click",null,function() {
        
        return false;
    });
    
    $(".webpage-link").live("click",null,function() {
        $("#displayBookmark").attr("src",$(this).attr("url"));
    });
    
    $(".webpage-link-out").live("click",null,function() {
        var url=$(this).parent("li").attr("url");
        
        window.open(url);
        
        return false;
    })
}


/******************Misc tests
 * 
 */

function buildTreeFromStaticData() {
    var $treeContainer=$("#tree");
    
    var $parentTagLi=uiCreateTag("tag1");
   
    var $parentTagUl=$("<ul class='collapsible'></ul>");
   
    var $childrenWebpageLi=uiCreateWebpage("title1");
   
    $parentTagUl.append($childrenWebpageLi);
    $parentTagLi.append($parentTagUl);
   
    $treeContainer.append($parentTagLi);
   
}